<div class="container-fluid">
	<h4 class="c-grey-900 mT-10 mB-30" th:text="#{user.admin.title}"></h4>
	<div class="row">
		<div class="col-md-12">
			<div class="bgc-white bd bdrs-3 p-20 mB-20">
				<h4 class="c-grey-900 mB-20" th:text="#{table.user.title}"></h4>
				<table id="userTable" class="table table-striped table-bordered" 
					cellspacing="0" width="100%">
					<thead>
						<tr>
							<!-- Columna oculta para el identificador de usuario -->
							<th></th>
							<th th:text="#{table.user.login}"></th>
							<th th:text="#{table.user.name}"></th>
							<th th:text="#{table.user.surname}"></th>
							<th th:text="#{table.user.password}"></th>
							<th th:text="#{table.user.email}"></th>
							<th th:text="#{table.user.cert.correct}"></th>
						</tr>
					</thead>
				</table>
			</div>
		</div>
	</div>
</div>

<div class="modal" tabindex="-1" role="dialog" id="modalEditAdmin">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<h4 class="modal-title" th:text="#{table.user.action.edit}"></h4>
				<button type="button" class="close" data-dismiss="modal" aria-label="Cerrar">
					<span aria-hidden="true">&times;</span>
				</button>
			</div>
			<div class="modal-body">
				<form name="altEditor-form" role="form" id="userFormEdit" th:object="${userformEdit}" th:action="@{/saveuseredit}" method="post">
					<input type='hidden' class='primarykey' id="idUserFireEdit" th:field="*{idUserFireEdit}">
					
					<div class="form-group-modal">
						
							<label for="nameEdit" class="col-form-label" th:text="#{form.user.name}"></label>
							<script th:inline="javascript">
								/*<![CDATA[*/
								    var messageName = /*[[#{form.user.name.pattern}]]*/ 'default';
								/*]]>*/
							</script>
							<input onblur="validate(this,messageName);" type="text" id="nameEdit" th:field="*{nameEdit}" style="overflow:hidden" class="form-control" required pattern=".{3,15}" />
							<div id="invalid-name" class="invalid-feedback" ></div>
						
						<div style="clear:both;"/>
					</div>
					
					<div class="form-group-modal">
						
							<label for="surnamesEdit" class="col-form-label" th:text="#{form.user.surnames}"></label>
							<script th:inline="javascript">
								/*<![CDATA[*/
								    var messageSurname = /*[[#{form.user.surnames.pattern}]]*/ 'default';
								/*]]>*/
							</script>
							<input onblur="validate(this,messageSurname);" type="text" id="surnamesEdit" th:field="*{surnamesEdit}" style="overflow:hidden" class="form-control" required pattern=".{3,30}"/>
							<div id="invalid-surnames" class="invalid-feedback" ></div>
						
						<div style="clear:both;"/>
					</div>
					
					<div class="form-group-modal">
						
							<label for="usernameEdit" class="col-form-label" th:text="#{form.user.login}"></label>
							<script th:inline="javascript">
								/*<![CDATA[*/
								    var messageLogin = /*[[#{form.user.login.pattern}]]*/ 'default';
								/*]]>*/
							</script>
							<input onblur="validate(this,messageLogin);" type="text" id="usernameEdit" th:field="*{usernameEdit}" style="overflow:hidden" class="form-control" required pattern=".{5,30}"/>
							<div id="invalid-login" class="invalid-feedback" ></div>
						
						<div style="clear:both;"/>
					</div>
					
					<div class="form-group-modal">
						
							<label for="emailEdit" class="col-form-label" th:text="#{form.user.email}"></label>
							<script th:inline="javascript">
								/*<![CDATA[*/
								    var messageEmail = /*[[#{form.user.email.pattern}]]*/ 'default';
								/*]]>*/
							</script>
							<input onblur="validate(this,messageEmail);" type="email" id="emailEdit" th:field="*{emailEdit}" style="overflow:hidden" class="form-control" required/>
							<div id="invalid-email" class="invalid-feedback" ></div>
						
						<div style="clear:both;"/>
					</div>
				</form>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-default" data-dismiss="modal" th:text="#{button.close}"></button>
				<button type="submit" id="editBtn" class="btn btn-primary"th:text="#{button.save}"></button>
			</div>
		</div>
	</div>
</div>

<div class="modal" tabindex="-1" role="dialog" id="modalPassword">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<h4 class="modal-title" th:text="#{user.admin.changePassword}"></h4>
				<button type="button" class="close" data-dismiss="modal" aria-label="Cerrar">
					<span aria-hidden="true">&times;</span>
				</button>
			</div>
			<div class="modal-body">
				<form role="form" id="userFormPassword" th:object="${userFormPassword}" th:action="@{/saveuserpassword}" method="post">
					
					<input type='hidden' class='primarykey' id="idUserFirePass" th:field="*{idUserFirePass}">
					
					<div class="form-group-modal">
						<label for="oldPassword" class="col-form-label" th:text="#{form.user.oldPassword}"></label>
						<span id="oldPassword_span" class="badge bgc-red-50 c-red-700 p-10 lh-0 tt-c badge-pill"></span>
						<input type="password" style="display:none">
						<input type="password" id="oldPassword" th:field="*{oldPassword}" class="form-control" />
					</div>
					
					<div class="form-group-modal">
						<label for="password" class="col-form-label" th:text="#{form.user.password}"></label>
						<span id="password_span" class="badge bgc-red-50 c-red-700 p-10 lh-0 tt-c badge-pill"></span>
						<input type="password" id="password" th:field="*{password}" class="form-control" />
					</div>
					
					<div class="form-group-modal">
						<label for="confirmPassword" class="col-form-label" th:text="#{form.user.confirmPassword}"></label>
						<span id="confirmPassword_span" class="badge bgc-red-50 c-red-700 p-10 lh-0 tt-c badge-pill"></span>
						<input onblur="validateConfirmPassword();" type="password" id="confirmPassword" th:field="*{confirmPassword}" class="form-control" />
					</div>
				</form>

			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-default" data-dismiss="modal" th:text="#{button.close}"></button>
				<button type="submit" id="passwordBtn" class="btn btn-primary" th:text="#{button.save}"></button>
			</div>
		</div>
	</div>
</div>


<script th:inline="javascript">
$(document).ready(function() {
	
	var actionSave = /*[[@{/saveuser}]]*/;
	var actionDelete = /*[[@{/deleteuser}]]*/;
	var getusers = /*[[@{/usersdatatable}]]*/;
	var editTemplate = /*[[@{/edituser}]]*/;
	var addTemplate = /*[[@{/adduser}]]*/;
	var manageCertUser = /*[[@{/managecertuser}]]*/;
	var tbl = $('#userTable').DataTable({
		dom: 'Bfrtip',
	    select: 'single',
	    responsive: true,
	    altEditor: true,
	    buttons: [{text: 'Agregar',name: 'add'}, 
	    		  {extend: 'selected',text: 'Editar',name: 'editt',
	    			  action: function ( e, dt, node, config ) {
					  
						$('#modalEditAdmin').modal('show');
	    				  
	    				  for (var o = dt, a = [], e = 0; e < o.context[0].aoColumns.length; e++) a.push({
							id: o.context[0].aoColumns[e].mData,
							title: o.context[0].aoColumns[e].sTitle                
						  });
						  
						  var d = dt.rows({
	                        selected: !0
						  });
							
						  var idUserFireEdit = d.data()[0][a[0].id];
						  var name = d.data()[0][a[1].id];
						  var surnames = d.data()[0][a[2].id];
						  var username = d.data()[0][a[3].id];
						  var email = d.data()[0][a[5].id];
						  
						  $("#idUserFireEdit").val(idUserFireEdit);
						  $("#nameEdit").val(name);
						  $("#surnamesEdit").val(surnames);
						  $("#usernameEdit").val(username);
						  $("#emailEdit").val(email);
						
	    			  }
	    		  }, 
	    		  {extend: 'selected',text: 'Eliminar',name: 'delete'}, 
	    		  
					{extend: 'selected',text: 'Visualizar',name: 'manageCertificates',
		    			  action: function ( e, dt, node, config ) {
		    				  
							  for (var o = dt, a = [], e = 0; e < o.context[0].aoColumns.length; e++) a.push({
								id: o.context[0].aoColumns[e].mData,
								title: o.context[0].aoColumns[e].sTitle                
							  });
							  
							  var d = dt.rows({
		                        selected: !0
							  });
								
							  var idUserFireEdit = d.data()[0][a[0].id];
							  $("#idUserFireEdit").val(idUserFireEdit);
		            		  loadIntoAjax('formMenu', manageCertUser + "/" + idUserFireEdit, 'optionReplacement', 'GET', null, true); return false;
		    				}
						}],
	    "iTotalRecords": "totalElements",
        "iTotalDisplayRecords": "numberOfElements",
	    
		"processing": true,
	    "serverSide": true,
		"ajax": {
	        "url": getusers,
	        "dataSrc" : "data",
	        "data": function (data) {
	        	// Datos a pasar al modal
	            data.formId = "userForm";
	            data.addTemplate = addTemplate;
	        }
	    },
	    "language": {
	        "url": "js/datatables/i18n/spanish.json",
	        select: {
	            rows: {
	                _: "%d filas seleccionadas",
	                1: "1 fila seleccionada"
	            }
	          }
	        },
	       
		"columns": [
	        { "data": "idUserFire",
	          "visible": false},
	        { "data": "name" },
	        { "data": "surnames" },
	        { "data": "username" },
	        { "data": "password",
	          "visible": false},
	        { "data": "email" },
	        { "data": "someCertNotValid" }
	        ]
		}).on('crudaction', function(e, accion, idUserFire, data, rowindex){
		    // e          Evento Jquery
		    // accion     [add|edit|delete]
		    // pkid       Primer campo en la data [id]                ... en add,    retorna null
		    // data       Los campos adicionales  [campo_1, campo_n]  ... en delete, retorna null
		    // rowindex   El index de la fila para el dataTable       ... en add,    retorna null
		    
		    $('#altEditor-modal .modal-body .alert').remove();
		    // Se muestra la capa 'cargando...'
		    loading();
		    
		    switch(accion){
		        case 'add':
		        	if ($('#userForm')[0].checkValidity() === false) {
		        		// Se oculta la capa 'cargando...'
		        		hide();
		                event.stopPropagation();
		                
		                $('#userForm *').filter(':input').each(function(){
		            	    		            	    
		                	if(!$(this)[0].checkValidity())
		            	    {
		            	  	 $("#invalid-" + $(this).attr('id')).html();
		            	  	 $("#" + $(this).attr('id')).addClass("is-invalid");
		            	    } else {
		            	  	 $("#" + $(this).attr('id')).removeClass("is-invalid");
		            	    }
		            	    
		            	});
		                
		                // Esto es necesario para forzar que se muestren mensajes de validación de cliente
		                $('<input type="submit">').hide().appendTo($('#userForm')).click().remove();
		            } else {
		            	if ($('#passwordAdd').val() != $('#confirmPasswordAdd').val()){
		            		$('#userForm').append('<div id="errorModalUser3" class="alert alert-danger" role="alert"><strong>' + [[#{user.admin.error.confPassword}]] + '</strong></div>');
		            		hide();
		            	}else{
		            		
		            		$("#userForm input")[4].value = $('#passwordAdd').val();
		            		$("#userForm input")[5].value = $('#confirmPasswordAdd').val();
		            		
		            		$.ajax(actionSave, {
				            	dataType : 'json',
				            	contentType:'application/json',
				                data : JSON.stringify($("#userForm").serializeJSON()),
				                type:'POST',
				                success: function(data){
				                	var errores = JSON.parse(data.error);
				  				  	
				  				  	if (data.error != null){
										$('#userForm').append('<div id="errorModalUser2" class="alert alert-danger" role="alert"><strong>'+ errores["password_span"] +'</strong></div>');
				  				  	}else{
					  				  	tbl.row.add($(data.data)).draw(false);
		    		                    
					                    $('#altEditor-modal .modal-body .alert').remove();
					                    $('#altEditor-modal').modal('hide');
										
										if ($('#errorModalUser').length > 0){
											$('#errorModalUser').remove();
										}
										if ($('#errorModalUser2').length > 0){
											$('#errorModalUser2').remove();
										}
										if ($('#errorModalUser3').length > 0){
											$('#errorModalUser3').remove();
										}
				  				  	}
									
				            		// Se oculta la capa 'cargando...'
				            		hide();
				                    
				                },
				                error:function(data){
				                	hide();
				                	$('#errorModalUser').remove();
				                	$('#userForm').append('<div id="errorModalUser" class="alert alert-danger" role="alert"><strong>' + [[#{user.admin.error.sameName}]] + '</strong></div>');
				                }
				            });
		            	}
		            }
		        	$('#userForm').addClass('was-validated');
		            break;
		        case 'delete':
		            $.ajax(actionDelete,{
		            	data:$.param({'id':data.idUserFire, 'index':rowindex}),
		                type:'POST',
		                success: function(data){
		                    
		                	// Se oculta la capa 'cargando...'
		                	hide();
		                    tbl.row(data.index).remove().draw();
		                    
		                    $('#altEditor-modal .modal-body .alert').remove();
		                    $('#altEditor-modal').modal('hide');
		                },
		                error:function(){}
		            });
		            break;
		        default:
		            $('#altEditor-modal .modal-body .alert').remove();
		            $('#altEditor-modal .modal-body').append('<div class="alert alert-danger" role="alert"><strong>' + [[#{alarm.admin.error.NotAuthorized}]] + '</strong></div>');
		            break;
		    }
		});
		
	$( "#passwordBtn" ).click(function( event ) {
	  event.preventDefault();
		
	  var formData = JSON.stringify($("#userFormPassword").serializeJSON());
	  var url = /*[[@{/saveuserpassword}]]*/;
	  
	  loading();
	  
	  $.ajax({
		  type: "POST",
		  url: url,
		  data: formData,
		  success: function(data){
			hide();
			
			switch(data){
			case 0:
				$('#errorModalUser').remove();
				$('#modalPassword').modal('hide');
				break;
			case -1:
				$('#errorModalUser').remove();
				$('#userFormPassword').append('<div id="errorModalUser" class="alert alert-danger" role="alert"><strong>' + [[#{user.admin.error.oldPassword}]] + '</strong></div>');
				break;
			case -2:
				$('#errorModalUser').remove();
				$('#userFormPassword').append('<div id="errorModalUser" class="alert alert-danger" role="alert"><strong>' + [[#{message.error}]] + '</strong></div>');
				break;
			default:
				if (data != null){
					jQuery.each(data, function(i, val) {
						$('#userFormPassword *').filter('span').each(function(){
							if (i == $(this).attr('id')){
								$("#" + i).text(val);
							}
						});
					});
				}
			}
		  },
		  error:function(){
			  hide();
			  $('#errorModalUser').remove();
			  $('#userFormPassword').append('<div id="errorModalUser" class="alert alert-danger" role="alert"><strong>' + [[#{message.error}]] + '</strong></div>');
		  },
		  dataType: "json",
		  contentType : "application/json"
		});
	});
	
	$( "#editBtn" ).click(function( event ) {
		  event.preventDefault();
			
		  var formData = JSON.stringify($("#userFormEdit").serializeJSON());
		  var url = /*[[@{/saveuseredit}]]*/;
		  
		  loading();
		  
		  $.ajax({
			  type: "POST",
			  url: url,
			  data: formData,
			  success: function(data){
				hide();
				
				tbl.row.add($(data.data)).draw(false);
				
				if ($('#errorModalEdit').length > 0){
					$('#errorModalEdit').remove();
				}
				
				$('#modalEditAdmin').modal('hide');
				
			  },
			  error:function(){
				  hide();
				  $('#errorModalEdit').remove();
				  $('#userFormEdit').append('<div id="errorModalEdit" class="alert alert-danger" role="alert"><strong>' + [[#{message.error}]] + '</strong></div>');
			  },
			  dataType: "json",
			  contentType : "application/json"
		});
	});
});	

</script>